package com.niannian.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.MyDate;
import com.niannian.util.UmengPage;
import com.niannian.adapter.NewssAdaper;
import com.niannian.bean.NewssBean;
import com.niannian.util.LoadDataUtil;
import com.niannian.view.PullToRefreshListView;
import com.niannian.view.PullToRefreshListView.IXListViewListener;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

;

/**
 * 消息
 * 
 * @author shengl
 * 
 */
public class NewssActivity extends BaseActivity {
	private PullToRefreshListView list_news_info;// 消息显示列表
	private NewssAdaper nAdapter;// 消息适配器

	private LoadData loadData;// 加载动态
	TextView tv_no_news_data;// 没有数据的提示
	public static boolean isForeground = false;
	TextView tv_date_tip_count;
	NewssBean TNewssCount = new NewssBean();// 提醒消息数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newss);
		initView();
		setLister();
		initTopView();
		loadData = new LoadData();
		loadData.setContext(this);
		loadData.loadOnlyDb(false, getParameters());
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				loadData.refresh(getParameters());

			}
		}, 1000);

		registerMessageReceiver();
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.GONE);
		iv_top_left2.setVisibility(View.VISIBLE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.GONE);
		top_title2.setVisibility(View.GONE);

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.VISIBLE);
		iv_top_right.setImageResource(R.drawable.add_member);
		iv_top_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				initPopuwindow();
			}
		});
	}

	LinearLayout ll_push_regards, ll_date_tip;

	private void initView() {

		ll_push_regards = (LinearLayout) findViewById(R.id.ll_push_regards);
		ll_date_tip = (LinearLayout) findViewById(R.id.ll_date_tip);

		list_news_info = (PullToRefreshListView) findViewById(R.id.list_news_info);
		list_news_info.setXListViewListener(xListViewListener);
		list_news_info.setPullLoadEnable(false);
		// list_news_info.forceShowHeaderRefresh();
		nAdapter = new NewssAdaper(this);
		list_news_info.setAdapter(nAdapter);
		nAdapter.setAdapter(nAdapter);
		// 没有数据的时候显示
		tv_no_news_data = (TextView) findViewById(R.id.tv_news_no_data);
		tv_no_news_data.setVisibility(View.VISIBLE);

		tv_date_tip_count = (TextView) findViewById(R.id.tv_date_tip_count);

	}

	private void updateContent(List<NewssBean> beans) {
		if (nAdapter == null) {
			nAdapter = new NewssAdaper(this);
			list_news_info.setAdapter(nAdapter);
		}
		nAdapter.getNDatasList().addAll(beans);
		nAdapter.notifyDataSetChanged();

		if (nAdapter.getCount() > 0) {
			tv_no_news_data.setVisibility(View.GONE);
		} else {
			tv_no_news_data.setVisibility(View.VISIBLE);
		}
	}

	private void setLister() {
		ll_push_regards.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle pBundle = new Bundle();
				pBundle.putInt("from", PushRegardsActivity.FROM_PUSH_REGARDS);
				openActivity(PushRegardsActivity.class, pBundle);
				getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
				MobclickAgent.onEvent(NewssActivity.this, UmengPage.dondon_add_regard);
			}
		});
		ll_date_tip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putInt("id", TNewssCount.getSender());
				openActivity(DateTipActivity.class, bundle);
				getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
				tv_date_tip_count.setVisibility(View.GONE);
				NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
				notiManager.cancelAll();
			}
		});
	}

	private Map<String, Object> getParameters() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lasttime", 0);
		return map;
	}

	class LoadData extends LoadDataUtil {

		@Override
		protected String runServerTask(Map<String, Object> parameters) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			return nnSyncApi.getNewssInfo(lasttime);
		}

		protected void serverTaskFinally(Map<String, Object> params) {
			onLoad();
			list_news_info.setPullLoadEnable(false);
		}

		@Override
		protected boolean handleServerSuccess(JSONObject json, Map<String, Object> parameters) {
			onLoad();
			list_news_info.setPullLoadEnable(false);
			try {
				if (json.getInt("code") == ErrorCode.OK) {

					int lasttime = 0;
					if (!Common.empty(parameters.get("lasttime"))) {
						lasttime = (Integer) parameters.get("lasttime");
					}
					databaseapi.updateNewss(userInfoManager.id, json.getJSONArray("data"), lasttime, tv_date_tip_count, TNewssCount);
					MessageRecieveManager.total_count = json.getInt("total_count");
					if (MessageRecieveManager.total_count > 0) {
						Intent msgIntent = new Intent(MessageRecieveManager.NEWSS_TOTAL_COUNT_ACTION);
						sendBroadcast(msgIntent);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected boolean loadMoreDB(Map<String, Object> parameters, boolean refresh) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			List<NewssBean> ndata = databaseapi.loadNewss(userInfoManager.id, lasttime);
			list_news_info.listNotData(true);

			if (ndata != null) {

				if (lasttime == 0) {
					nAdapter.getNDatasList().clear();
				}
				updateContent(ndata);
			}
			return false;
		}
	}

	private IXListViewListener xListViewListener = new IXListViewListener() {
		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					loadData.refresh(getParameters());
				}
			}, 500);
		}

		@Override
		public void onLoadMore() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					NewssBean last = null;
					try {
						last = (NewssBean) nAdapter.getItem((nAdapter.getCount() - 1));
					} catch (Exception e) {
						last = null;
					}
					if (last != null) {
						map.put("lasttime", last.getItem_time());
					} else {
						map.put("lasttime", 0);
					}
					loadData.load(map);
				}
			}, 150);
		}
	};

	private void onLoad() {// 显示拉出来时候的一些信息
		list_news_info.stopRefresh();
		list_news_info.stopLoadMore();
		list_news_info.setRefreshTime(MyDate.getDate());
	}

	PopupWindow RightPopupWindow;

	LinearLayout ll_family, ll_push_regardss, ll_push_family_news, ll_add_date_tip;

	@SuppressWarnings("deprecation")
	private void initPopuwindow() {
		View mMenuView = null;
		if (RightPopupWindow == null) {
			mMenuView = LayoutInflater.from(NewssActivity.this).inflate(R.layout.main_choose_popupwindow, null);

			ll_family = (LinearLayout) mMenuView.findViewById(R.id.ll_family);
			ll_push_regardss = (LinearLayout) mMenuView.findViewById(R.id.ll_push_regards);
			ll_push_family_news = (LinearLayout) mMenuView.findViewById(R.id.ll_push_family_news);
			ll_add_date_tip = (LinearLayout) mMenuView.findViewById(R.id.ll_add_date_tip);

			ll_family.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle bundle = new Bundle();
					bundle.putInt("ACTION_TYPE", 3);
					openActivity(AddFamilyMemberActivity.class, bundle);
					getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					RightPopupWindow.dismiss();
				}
			});
			ll_push_regardss.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle pBundle = new Bundle();
					pBundle.putInt("from", PushRegardsActivity.FROM_PUSH_REGARDS);
					openActivity(PushRegardsActivity.class, pBundle);
					getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					RightPopupWindow.dismiss();
					MobclickAgent.onEvent(NewssActivity.this, UmengPage.plus_add_regard);
				}
			});
			ll_push_family_news.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle pBundle = new Bundle();
					pBundle.putInt("from", PushRegardsActivity.FROM_push_news);
					openActivity(PushRegardsActivity.class, pBundle);
					getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					RightPopupWindow.dismiss();
				}
			});
			ll_add_date_tip.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					openActivity(AddDateTipActivity.class, DateTipActivity.PUSH_REGARDS_TIP);
					getParent().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					RightPopupWindow.dismiss();
				}
			});
			RightPopupWindow = new PopupWindow(mMenuView, mScreenWidth / 2 + 60, LayoutParams.WRAP_CONTENT, true);
			RightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			RightPopupWindow.setOutsideTouchable(true);
			RightPopupWindow.setAnimationStyle(R.style.Popup_Animation_DownScale);
		} else {
			mMenuView = RightPopupWindow.getContentView();
		}

		RightPopupWindow.showAsDropDown(iv_top_right, -0, -0);

	}

	public class NotificationReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (MessageRecieveManager.JPUSH_NEWSS_ACTION.equals(action)) {
				loadData.refresh(getParameters());
			} else if (MessageRecieveManager.UPDATA_NEWSS_TOTAL_COUNT_ACTION.equals(action)) {
				try {
					String msg_type = intent.getStringExtra("msg_type");
					int newss_count = 0;
					if (msg_type.equals("R")) {
						newss_count = getNewssCount(intent.getIntExtra("sender", 0));
					} else if ((msg_type.equals("T"))) {
						newss_count = Integer.parseInt(tv_date_tip_count.getText().toString().trim());
						tv_date_tip_count.setVisibility(View.GONE);
						tv_date_tip_count.setText("0");
					} else if ((msg_type.equals("S"))) {
						newss_count = getNewssCount("S");
					}

					if (MessageRecieveManager.total_count > 0) {
						MessageRecieveManager.total_count = MessageRecieveManager.total_count - newss_count;
						Intent msgIntent = new Intent(MessageRecieveManager.NEWSS_TOTAL_COUNT_ACTION);
						sendBroadcast(msgIntent);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		}
	}

	NotificationReceiver notificationReceiver;

	public void registerMessageReceiver() {
		notificationReceiver = new NotificationReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(MessageRecieveManager.MESSAGE_RECEIVED_PRIORITY_MAIN);
		filter.addAction(MessageRecieveManager.JPUSH_NEWSS_ACTION);
		filter.addAction(MessageRecieveManager.UPDATA_NEWSS_TOTAL_COUNT_ACTION);

		NewssActivity.this.registerReceiver(notificationReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(notificationReceiver);
		super.onDestroy();
	}

	private int getNewssCount(int sender) {
		int newss_count = 0;
		for (int i = 0; i < nAdapter.getNDatasList().size(); i++) {
			if (sender == nAdapter.getNDatasList().get(i).getSender()) {
				newss_count = nAdapter.getNDatasList().get(i).getMsg_count();
				nAdapter.getNDatasList().get(i).setMsg_count(0);
				nAdapter.notifyDataSetChanged();
				break;
			}
		}
		return newss_count;
	}

	private int getNewssCount(String msg_type) {
		int newss_count = 0;
		for (int i = 0; i < nAdapter.getNDatasList().size(); i++) {
			if (msg_type.equals(nAdapter.getNDatasList().get(i).getMsg_type())) {
				newss_count = nAdapter.getNDatasList().get(i).getMsg_count();
				nAdapter.getNDatasList().get(i).setMsg_count(0);
				nAdapter.notifyDataSetChanged();
				break;
			}
		}
		return newss_count;
	}

	@Override
	public void onBackPressed() {
		exit();
	}

	@Override
	public void onResume() {
		super.onResume();
		isForeground = true;
		MobclickAgent.onPageStart(UmengPage.dondon_face);
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		isForeground = false;
		MobclickAgent.onPageEnd(UmengPage.dondon_face);
		MobclickAgent.onPause(this);
	}
}
